package com.lepu.app.fun.index.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.app.utils.LoginUtil;
import com.app.utils.Setting;
import com.app.utils.UmengEvent;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UmengHelper;
import com.core.lib.widget.GoogleRefreshLayout;
import com.core.lib.widget.GoogleRefreshLayout.OnLoadListener;
import com.lepu.app.fun.bbs.bean.BeanBbs;
import com.lepu.app.fun.index.adapter.IndexBookAdapter;
import com.lepu.app.fun.index.bean.BeanIndexBook;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.pasm.R;

public class IndexBookActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener ,AsyncRequest,
		OnRefreshListener, OnLoadListener{
	private static final String REQUEST_DATA = "request_data";
	private static final String REQUEST_DATA_MORE = "request_data_more";

	private static final int MSG_DATA_SUCCESS = 10;
	private static final int MSG_DATA_FAIL = 11;
	private static final int MSG_DATA_MORE_SUCCESS = 12;
	private static final int MSG_DATA_MORE_FAIL = 13;


	// ========================================================================
	private GoogleRefreshLayout mGoogleRefreshLayout = null;
	private ListView mDataListView = null;
	private IndexBookAdapter mDataAdapter = null;
	private ArrayList<BeanIndexBook> mDataArrayList = null;
	
	private int mCurrentPage = 1;
	private String mCurrentDate = "";
	@Override
	public void onCreate(Bundle savedInstanceState) {
		mNeedDefaultUmeng = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.index_book_activity);

		init();
	}

    @Override
	public void onResume() {
        super.onResume();

        UmengHelper.onResume(this, UmengEvent.page_shouye_tongxinshufang);
    }

    @Override
	public void onPause() {
        super.onPause();

        UmengHelper.onPause(this, UmengEvent.page_shouye_tongxinshufang);
    }
	
	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}
	
	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	
	private void showHideNoDataLayout(boolean isShow)
	{
		LinearLayout noDataLayout = (LinearLayout)findViewById(R.id.noDataLayout);
		if(noDataLayout != null)
		{
			if(isShow)
			{
				noDataLayout.setVisibility(View.VISIBLE);
			}else{
				noDataLayout.setVisibility(View.GONE);
			}
		}
	}
	
	private void showFirstLoadDataLayout(boolean isShow)
	{
		LinearLayout firstLoadDataLayout = (LinearLayout) findViewById(R.id.firstLoadDataLayout);
		if(firstLoadDataLayout != null)
		{
			if(isShow)
			{
				if(mDataArrayList == null || mDataArrayList.size() == 0)
				{
					firstLoadDataLayout.setVisibility(View.VISIBLE);
				}
				
				LinearLayout noDataLayout = (LinearLayout) findViewById(R.id.noDataLayout);
				noDataLayout.setVisibility(View.GONE);
				
			}else{
				firstLoadDataLayout.setVisibility(View.GONE);
			}
		}
	}

	/**
	 * 初始化方法
	 */
	@SuppressWarnings("deprecation")
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("同心书坊");
		topbar.setonTopbarNewLeftLayoutListener(this);
		
		mDataListView = (ListView)findViewById(R.id.dataListView);
		mGoogleRefreshLayout = (GoogleRefreshLayout) findViewById(R.id.swipeLayout);
		mGoogleRefreshLayout.setOnRefreshListener(this);
		mGoogleRefreshLayout.setOnLoadListener(this);
		mGoogleRefreshLayout.setColorScheme(R.color.color_listview_refresh_1,
											R.color.color_listview_refresh_2,
											R.color.color_listview_refresh_3,
											R.color.color_listview_refresh_4);
		
		mDataArrayList = new ArrayList<BeanIndexBook>();
		mDataArrayList = BeanIndexBook.getTestData();
		
		mDataAdapter = new IndexBookAdapter(IndexBookActivity.this,mDataArrayList);
		mDataListView.setAdapter(mDataAdapter);
		mGoogleRefreshLayout.setLoadMoreFinish(true);
		
		mDataListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {

				BeanIndexBook book = mDataArrayList.get(arg2);

				if(book.index == 1)
				{
					UmengHelper.CustomEvent(IndexBookActivity.this,UmengEvent.event_tongxinshufang_zhijiarensheng);
				}else if(book.index == 2)
				{
					UmengHelper.CustomEvent(IndexBookActivity.this,UmengEvent.event_tongxinshufang_jiankangshouce);
				}

				Intent intent = new Intent(IndexBookActivity.this,IndexBookDetailActivity.class);
				Bundle bundler = new Bundle();
				bundler.putSerializable("book",book );
				intent.putExtras(bundler);
				startActivity(intent, true);
			}
		});
		
		//request(false);
	}

	//请求数据
	public void request(boolean isMore) {

		String request = "";
		int page = 1;
		if (isMore) {
			request = REQUEST_DATA_MORE;
			page = (mCurrentPage + 1);
		} else {
			request = REQUEST_DATA;
			mCurrentPage = page;
		}

		String url = "";

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			if (LoginUtil.checkIsLogin()) {
				params.put("UserID", LoginUtil.getUserId());
			} else {
				params.put("UserID", -1);
			}
			
			params.put("LoginToken", LoginUtil.getLoginToken());
			
			url = Setting.getBbsListUrl();
			params.put("ForumID", 2);
			params.put("ThreadClassID", 0);

			params.put("RefreshTime", mCurrentDate);
			params.put("PageIndex", page);
			params.put("PageSize", Setting.PAGE_SIZE);
			
		} catch (Exception e) {
		}
		map.put("ht", params);
		ApiClient.http_post(url, map, null, this, request, true);
	}

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {

		@SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_DATA_SUCCESS:
				
				//ArrayList<BeanIndexBook> dataList = (ArrayList<BeanIndexBook>) msg.obj;
				
				ArrayList<BeanIndexBook> dataList = BeanIndexBook.getTestData();
				if (dataList != null && dataList.size() > 0) {
					showHideNoDataLayout(false);
					mDataArrayList.clear();
					mDataArrayList.addAll(dataList);

				} else {
					UIHelper.showToast(IndexBookActivity.this, R.string.no_data);
                    showHideNoDataLayout(true);
					
					if (mDataArrayList != null && mDataArrayList.size() > 0) {
						mDataArrayList.clear();
					}
				}

				ImageView tempImageView = new ImageView(IndexBookActivity.this);
				mDataListView.addHeaderView(tempImageView);

				mDataAdapter = new IndexBookAdapter(IndexBookActivity.this,mDataArrayList);
				mDataListView.setAdapter(mDataAdapter);

				mDataListView.removeHeaderView(tempImageView);

				// 更新完后调用该方法结束刷新
				mGoogleRefreshLayout.setRefreshing(false);
				
				//第一次请求用这个
				showFirstLoadDataLayout(false);
				break;
			case MSG_DATA_FAIL:
				// 更新完后调用该方法结束刷新
				mGoogleRefreshLayout.setRefreshing(false);
				showFirstLoadDataLayout(false);
				showHideNoDataLayout(true);
				break;
			case MSG_DATA_MORE_SUCCESS:

				ArrayList<BeanIndexBook> dataMoreList = (ArrayList<BeanIndexBook>) msg.obj;
				
				if (dataMoreList != null && dataMoreList.size() > 0) {
					
				    mDataAdapter.notifyDataSetChanged();

					// 加载更多数据成功，page ++
					mCurrentPage++;
				} else {
					UIHelper.showToast(IndexBookActivity.this, R.string.no_data_more);
					mGoogleRefreshLayout.setLoadMoreFinish(true);
				}

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;
			case MSG_DATA_MORE_FAIL:

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;

			default:
				break;
			}
		};
	};

	@Override
	public void onLoad() {
		request(true);
	}

	@Override
	public void onRefresh() {
		request(false);
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_DATA)) {
			mCurrentDate = BeanBbs.parseJsonDate((String) data);
			ArrayList<BeanBbs> dataArraylist = BeanBbs.parseJsonData((String) data);

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_SUCCESS;
			msg.obj = dataArraylist;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			mCurrentDate = BeanBbs.parseJsonDate((String) data);
			ArrayList<BeanIndexBook> dataMoreArraylist = BeanIndexBook.parseJsonData((String) data);

			if (dataMoreArraylist != null && dataMoreArraylist.size() > 0) {
				mDataArrayList.addAll(dataMoreArraylist);
			}

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_MORE_SUCCESS;
			msg.obj = dataMoreArraylist;
			mHandler.sendMessage(msg);
		} 
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_DATA)) {
			mHandler.sendEmptyMessage(MSG_DATA_FAIL);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			mHandler.sendEmptyMessage(MSG_DATA_MORE_FAIL);
		} 
	}

}
